import datetime
import os.path

import ujson


class UChinaHoliday:
    """
    中国节假日类，从 holiday.json 中解析出放假情况, 文件路径在类实例初始化时指定
    holiday数据更新地址：https://timor.tech/api/holiday/year/{YEAR}
    本类提供方法有，获取所有休息日，获取所有工作日，判断某一天是否是工作日/休息日
    """
    def __init__(self, holiday_file_path):
        self.rest_set = set()
        self.work_set = set()
        self.holiday_json_file = holiday_file_path
        if not os.path.exists(holiday_file_path):
            raise FileNotFoundError(f"holiday json file not found, path:{holiday_file_path}")
        self.init_data()

    def init_data(self):
        """

        :return:
        """
        with open(self.holiday_json_file, 'r', encoding="utf-8") as f:
            holiday_json = ujson.load(f)

            cur_year = datetime.datetime.now().year
            if f"holiday_{cur_year}" in holiday_json:
                cur_holiday = holiday_json.get(f"holiday_{cur_year}")
            elif "holiday" in holiday_json:
                cur_holiday = holiday_json.get("holiday")
            else:
                raise ValueError("节假日配置文件中没有节假日的配置，请检查！")
            # 检查日期是否是当年
            test_date = cur_holiday.get("01-01").get("date")
            if not test_date.startswith(str(cur_year)):
                raise ValueError(f"节假日配置过期，不是{cur_year}的配置，请更新最新的节假日信息，"
                                 f"更新链接：https://timor.tech/api/holiday/year/{cur_year}")
            start_time = datetime.datetime.strptime(f"{cur_year}-01-01", "%Y-%m-%d")
            end_time = datetime.datetime.strptime(f"{cur_year}-12-31", "%Y-%m-%d")
            date_dict = dict()
            offset = datetime.timedelta(days=1)
            _date = start_time
            while _date <= end_time:
                month_day = str(_date.month).zfill(2) + "-" + str(_date.day).zfill(2)
                _res = cur_holiday.get(month_day, dict())
                if _res:
                    date_dict[(_date.month, _date.day)] = _res.get("holiday")
                else:
                    date_dict[(_date.month, _date.day)] = _date.weekday() > 4
                _date += offset

            for _month_day, is_holiday in date_dict.items():
                if is_holiday:
                    self.rest_set.add(_month_day)
                else:
                    self.work_set.add(_month_day)

    def get_rest_day(self):
        """
        获取所有休息日
        :return:
        """
        return self.rest_set

    def get_workday(self):
        """
        获取所有工作日
        :return:
        """
        return self.work_set

    def work(self, _datetime):
        """
        判断某一天是否是工作日
        :param _datetime:
        :return:
        """
        _key = (_datetime.month, _datetime.day)
        return _key in self.work_set

    def rest(self, _datetime):
        """
        判断某一天是否是休息日
        :param _datetime:
        :return:
        """
        _key = (_datetime.month, _datetime.day)
        return _key in self.rest_set

    @staticmethod
    def all(_datetime):
        """
        直接返回True，用于在统计所有日期数据时统一调用格式
        :param _datetime:
        :return:
        """
        return True